package twitter.clienttest;
import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import org.apache.log4j.*;
public class TwitterClient {
private Socket clientSocket = null;
private String server;
private int port;
static Logger logger = Logger.getLogger(ClientTest.class);
private String threadName;
public TwitterClient(String server,int port,String threadname)
{
	this.server=server;
	this.port=port;
	BasicConfigurator.configure();
	this.threadName=threadname;
	
	}
	

	public void sendHttpGetRequest(String key)
	{
		String query="GET /search?q="+key+" HTTP/1.1";
		logger.info(this.threadName+"**********Send a good http GET request: "+query+" 200 expected");
		
		sendHTTPRequest(server,query,port);
	}
	public void sendIncorrectFormatGet(String key)
	{
		String query="GET /search???q"+key+" HTTP/1.1";
		logger.info(this.threadName+"**********Send a incorrect format Get request: "+query+" 400 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendHttpPostRequest(String status)
	{
		String query="POST /status/update?status="+status+" HTTP/1.1";
		logger.info(this.threadName+"**********Send a good http Post request: "+query+" 204 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendIncorrectFormatPost(String status)
	{
		String query="POST /status/update????status="+status+" HTTP/1.1";
		logger.info(this.threadName+"**********Send a incorrect formate Post request: "+query +" 400 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendIncorrectURIGet(String key)
	{
		String query="GET /test?q="+key+" HTTP/1.1";
		logger.info(this.threadName+"**********Send an incorrect uri GET http request: "+query+" 404 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendIncorrectURIPost(String status)
	{
		String query="POST /status/what?status="+status+" HTTP/1.1";
		logger.info(this.threadName+"**********Send an incorrect uri POST http request: "+query+" 404 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendHttpGetIncorectVersion(String key)
	{
		String query="GET /search?q="+key+" HTTP/1.0";
		logger.info(this.threadName+"**********Send an  Incorrect HTTP version request : "+query+" 505 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendHttpPutRequest()
	{
		String query="PUT HTTP/1.1";
		logger.info(this.threadName+"***********Send a PUT request: "+query+" 501 expected");
		sendHTTPRequest(server,query,port);
	}
	public void sendHttpDeleteRequest()
	{
		String query="DELETE HTTP/1.1";
		logger.info(this.threadName+"**********Send a DELETE request : "+query+" 501 expected");
		sendHTTPRequest(server,query,port);
	}
	
	private String getKey(String queryString)
	{
		int start=queryString.indexOf("=");
		if(start==-1)
		{
			return "";
		}
		else
		{
			int end=queryString.indexOf("HTTP", start+1);
			return queryString.substring(start+1,end-1);
		}
		
	}
	private String addStartPart(String key,String queryString)
	{
		int end=queryString.indexOf("=");
		if(end!=-1)
		{
			String temp=queryString.substring(0,end+1);
			return temp+key;
		}
		else
		{
			return queryString;
		}
		
		
	}
	private String addEndPart(String firstPart,String queryString)
	{
		int start=queryString.indexOf(" HTTP");
		int end=queryString.length();
		return firstPart+queryString.substring(start, end);
	}
	private void sendHTTPRequest(String hostname, String queryString, int port) {
		
		
		PrintWriter out = null;
		BufferedReader in = null;

		
		try {
			clientSocket = new Socket(server, port);
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(clientSocket
					.getInputStream()));
		} catch (UnknownHostException e) {
			logger.error("Don't know about host: localhost.");
			System.exit(1);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		String key=getKey(queryString);
		String temp="";
		if(!key.equals(""))
		{
			try {
				key = URLEncoder.encode(key, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			temp=this.addStartPart(key, queryString);
			temp=this.addEndPart(temp,queryString);
			System.out.println(temp);
			queryString=temp;
		}
		constructHttpCommand(queryString,out);
		
		InputStream ins = null;
		try {
			ins = clientSocket.getInputStream();
			InputStreamReader isr = new InputStreamReader(ins);
			BufferedReader br = new BufferedReader(isr);
			int c;
			while ((c = br.read()) != -1) {
				System.out.print((char) c);
			}
			try {
				clientSocket.getOutputStream().close();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			out.close();
			isr.close();
			br.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		out.close();
		
		try {
			in.close();
			ins.close();
			
			//clientSocket.getOutputStream().close();
			clientSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void constructHttpCommand(String queryString, PrintWriter out) {
		
		
		String request = "";
		
			request = queryString+"\r\n";
			out.print(request);
			out.print("Accept: text/plain, text/html,text/xml, text/*\r\n");
			out.print("Host: "+server+":"+port+"\r\n");
			out.print("Connection: keep-alive\r\n");
			out.print("\r\n");
			out.flush();
			

	}
}


